package com.th.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.th.common.domain.UsOrder;
import com.th.common.domain.UsOrderRequire;
import com.th.common.domain.UsSessionToken;
import com.th.common.dto.OrderAndRequireDTO;
import com.th.common.exception.BaseServiceException;
import com.th.common.mybatis.query.QueryWrapperX;
import com.th.common.response.CommonResponse;
import com.th.common.response.PageResult;
import com.th.common.vo.OrderAndRequireVO;
import com.th.service.UsOrderRequireService;
import com.th.service.UsOrderService;
import com.th.service.UsSessionTokenService;
import com.th.service.UsUserService;
import com.th.service.impl.UsUserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Objects;

@RestController
@Api(tags = "企业接口")
@RequestMapping("/api/UsOrder")
public class UsOrderController {


    @Resource
    private UsOrderService usOrderService;

    @Autowired
    private UsSessionTokenService usSessionTokenService;

    @Resource
    private UsOrderRequireService usOrderRequireService;

    /**
     * 新增订单
     *
     * @param orderAndRequireDTO
     * @return
     */
    @ApiOperation("新增订单")
    @PostMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public CommonResponse<String> save(@RequestBody OrderAndRequireDTO orderAndRequireDTO,
                                       @RequestHeader("token") String token) {
        UsSessionToken usSessionTokenServiceToken = usSessionTokenService.getToken(token);
        Long userId = usSessionTokenServiceToken.getUserId();

        Date date = new Date();

        UsOrder usOrder = new UsOrder();
        BeanUtils.copyProperties(orderAndRequireDTO, usOrder);

        usOrder.setCreateTime(date);
        usOrder.setUpdateTime(date);

        usOrder.setUserId(userId);
        boolean isSuccess = usOrderService.save(usOrder);
        if (!isSuccess) {
            throw new BaseServiceException(500, "订单创建失败");
        }

        UsOrderRequire usOrderRequire = new UsOrderRequire();
        BeanUtils.copyProperties(orderAndRequireDTO, usOrderRequire);
        usOrderRequire.setOrderId(usOrder.getId());
        usOrderRequire.setId(null);

        isSuccess = usOrderRequireService.save(usOrderRequire);
        if (!isSuccess) {
            throw new BaseServiceException(500, "订单创建失败");
        }

        return CommonResponse.success("订单创建成功");
    }


    @PostMapping("/update")
    @ApiOperation("根据订单id修改订单信息")
    @Transactional(rollbackFor = Exception.class)
    public CommonResponse<String> updateById(@RequestBody OrderAndRequireDTO orderAndRequireDTO,
                                             @RequestHeader("token") String token) {

            UsSessionToken usSessionTokenServiceToken = usSessionTokenService.getToken(token);
            Long userId = usSessionTokenServiceToken.getUserId();
            //修改前查看该订单是否存在
            QueryWrapper<UsOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", orderAndRequireDTO.getId());
            UsOrder order = usOrderService.getOne(queryWrapper);

            if (order == null) {
                throw new BaseServiceException(500, "订单修改失败");
            }

            if (!Objects.equals(userId, order.getUserId())) {
                throw new BaseServiceException(501, "无权修改");
            }

//            order.setUserId(userId);

            BeanUtils.copyProperties(orderAndRequireDTO, order);
            Date date = new Date();
            order.setUpdateTime(date);
            boolean isSuccess = usOrderService.updateById(order);
            if (!isSuccess) {
                throw new BaseServiceException(500, "订单修改失败");
            }

            LambdaQueryWrapper<UsOrderRequire> usOrderRequireLambdaQueryWrapper = new LambdaQueryWrapper<>();
            usOrderRequireLambdaQueryWrapper.eq(UsOrderRequire::getOrderId, orderAndRequireDTO.getId());
            UsOrderRequire usOrderRequire = usOrderRequireService.getOne(usOrderRequireLambdaQueryWrapper);

            Long id = usOrderRequire.getId();
            BeanUtils.copyProperties(orderAndRequireDTO, usOrderRequire);
            usOrderRequire.setOrderId(order.getId());
            usOrderRequire.setId(id);

            isSuccess = usOrderRequireService.updateById(usOrderRequire);
            if (!isSuccess) {
                throw new BaseServiceException(500, "订单修改失败");
            }

            return CommonResponse.success("订单修改成功");
        }

    /**
     * 根据订单id删除订单信息
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation("根据订单id删除订单信息")
    @Transactional(rollbackFor = Exception.class)
    public CommonResponse<String> deleteById(@PathVariable("id") Long id) {

        //TODO: 删需求
//        QueryWrapper<UsOrder> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("id",id);
        //删除前要查询该订单是否存在
        usOrderService.removeById(id);

        LambdaQueryWrapper<UsOrderRequire> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UsOrderRequire::getOrderId,id);

        usOrderRequireService.remove(queryWrapper);

        return CommonResponse.success("订单删除成功");
    }


    @ApiOperation("根据订单id查询订单信息")
    @GetMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    public CommonResponse<OrderAndRequireVO> getById(@PathVariable("id") Long id) {

        //TODO: 加订单需求

        UsOrder usOrder = usOrderService.getById(id);

        if (usOrder != null) {

            LambdaQueryWrapper<UsOrderRequire> usOrderRequireLambdaQueryWrapper = new LambdaQueryWrapper<>();
            usOrderRequireLambdaQueryWrapper.eq(UsOrderRequire::getOrderId, usOrder.getId());
            UsOrderRequire usOrderRequire = usOrderRequireService.getOne(usOrderRequireLambdaQueryWrapper);
            if (Objects.isNull(usOrderRequire)) {
                throw new BaseServiceException(500, "error");
            }

            OrderAndRequireVO orderAndRequireVO = new OrderAndRequireVO();
            orderAndRequireVO.setOrder(usOrder);
            orderAndRequireVO.setOrderRequire(usOrderRequire);

            return CommonResponse.success(orderAndRequireVO);
        } else {
            return CommonResponse.error(5, "查询不到要操作的信息");
        }
    }


    @ApiOperation("分页查询企业订单信息")
    @GetMapping("/{page}/{pageSize}")
    public CommonResponse<PageResult<UsOrder>> Page(
            @PathVariable("page") int page,
            @PathVariable("pageSize") int pageSize,
            @RequestHeader("token") String token,
            @RequestParam(required = false, value = "startingTime") String startingTimeStr,
            @RequestParam(required = false, value = "endingTime") String endingTimeStr,
            @RequestParam(required = false) String title) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


        LocalDateTime startingTime = null;
        if (Objects.nonNull(startingTimeStr)) {
            startingTime = LocalDateTime.parse(startingTimeStr, formatter);
        }
        LocalDateTime endingTime = null;
        if (Objects.nonNull(endingTimeStr)) {
            endingTime = LocalDateTime.parse(endingTimeStr, formatter);
        }


        UsSessionToken usSessionTokenServiceToken = usSessionTokenService.getToken(token);
        Long userId = usSessionTokenServiceToken.getUserId();
//        //分页构造器
        Page<UsOrder> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<UsOrder> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(UsOrder::getUserId, userId).like(Objects.nonNull(title), UsOrder::getTitle, title)
                .ge(Objects.nonNull(startingTimeStr), UsOrder::getUpdateTime, startingTime)
                .lt(Objects.nonNull(endingTimeStr), UsOrder::getUpdateTime, endingTime);

        usOrderService.page(pageInfo, queryWrapper);

        PageResult<UsOrder> result = new PageResult<>();
        result.setTotal(pageInfo.getTotal());
        result.setList(pageInfo.getRecords());

        return CommonResponse.success(result);
    }
}